package handler

import (
	"github.com/gin-gonic/gin"
	"house/api/requset"
	"house/api/resp"
	"house/internal/dao"
	"house/internal/model"
	"time"
)

// 添加预约
func AddReservation(c *gin.Context) {
	//接收参数
	var req requset.AddReservationReq
	if err := c.ShouldBind(&req); err != nil {
		resp.Error(c, 10000, "验证失败", err.Error())
		return
	}

	//业务逻辑
	//判断房源
	var house model.House
	dao.GetOneById(req.HouseId, &house)
	if house.Id == 0 {
		resp.Error(c, 10000, "房源不存在", nil)
		return
	}
	//判断时间
	reservationTime, err := time.Parse(time.DateTime, req.ReservationTime)
	if err != nil {
		resp.Error(c, 10000, "时间格式错误", nil)
		return
	}
	if time.Now().Unix() > reservationTime.Unix() {
		resp.Error(c, 10000, "预约时间小于当前时间", nil)
		return
	}
	//添加预约
	result := dao.Create(&model.HouseReservation{
		UserId:          c.GetUint("userId"),
		HouseId:         req.HouseId,
		ReservationTime: reservationTime,
	})
	if !result {
		resp.Error(c, 10000, "预约添加失败", false)
		return
	}

	//返回
	resp.Success(c, true)

}

// 取消预约
func DelReservation(c *gin.Context) {
	//接收参数
	var req requset.DelReservationReq
	if err := c.ShouldBind(&req); err != nil {
		resp.Error(c, 10000, "验证失败", err.Error())
		return
	}

	//业务逻辑
	var res model.HouseReservation
	dao.GetOneById(req.Id, &res)
	if res.Id == 0 {
		resp.Error(c, 10000, "预约不存在", false)
		return
	}
	result := dao.Delete(&model.HouseReservation{
		Id: req.Id,
	})
	if !result {
		resp.Error(c, 10000, "预约取消失败", false)
		return
	}

	//返回
	resp.Success(c, true)
}
